package com.sky.aspect;

import com.sky.anno.TableInject;
import com.sky.constant.AutoFillConstant;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Aspect
@Component
public class TableInjectAspect {
    /**
     * 切点
     * 1、mapper下的方法
     * 2、必须加@TableInject注解
     */
    @Pointcut("execution(* com.sky.mapper.*.*(..)) && @annotation(com.sky.anno.TableInject)")
    public void pt() {

    }

    @Before("pt()")
    public void before(JoinPoint jp) {
        //问题：我们需要在这个地方获取到执行的方法对象
        //通过方法对象才可以获取注解对象
        MethodSignature signature = (MethodSignature) jp.getSignature();
        //获取到在当前正在执行的方法对象
        Method method = signature.getMethod();

        //通过method去获取到注解对象
        TableInject annotation = method.getAnnotation(TableInject.class);

        //获取方法接收的参数
        //employee、category、dish、setmeal
        Object target = jp.getArgs()[0];
        OperationType operationType = annotation.value();

        //健壮性判断
        if (target == null || jp.getArgs().length == 0 || jp.getArgs().length > 1) {
            return;
        }

        //准备填充的数据：
        //当前时间
        LocalDateTime now = LocalDateTime.now();
        //当前登录用户的id
        Long currentId = BaseContext.getCurrentId();

        try {
            //通过放着获取对应的set方法
            Method createTimeMethod = target.getClass().getMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
            Method updateTimeMethod = target.getClass().getMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
            Method createUserMethod = target.getClass().getMethod(AutoFillConstant.SET_CREATE_USER, Long.class);
            Method updateUserMethod = target.getClass().getMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);

            switch (operationType) {
                case INSERT:
                    createTimeMethod.invoke(target, now);
                    updateTimeMethod.invoke(target, now);
                    createUserMethod.invoke(target, currentId);
                    updateUserMethod.invoke(target, currentId);
                    break;

                case UPDATE:
                    updateTimeMethod.invoke(target, now);
                    updateUserMethod.invoke(target, currentId);
                    break;
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
